/*
 * @Author: 张小平
 * @Date:   2025-05-01 
 * @Email:  qqshuqian@163.com 
 * @Copyright © 2024 aseyun. All rights reserved.
 */
/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from 'axios'
import store from '@/framework-core/store/';
import router from '@/framework-core/router/'
import { serialize } from '@/framework-core/utils/util'
import { ElMessage } from 'element-plus'
import website from '@/framework-core/config/website';
import NProgress from '@/framework-core/config/nprogress/index.js'
axios.defaults.timeout = 60000;
//返回其他状态吗
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500; // 默认的
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = false;
//HTTPrequest拦截
axios.interceptors.request.use(config => {
  NProgress.start() // 开启进度条
  const isToken = (config.headers || {}).isToken === false
  const token = store.getters.token
  if (token && !isToken) {
    config.headers[website.Authorization] = token// token
  }

  const meta = (config.meta || {});
  //headers中配置serialize为true开启序列化
  if (config.method === 'post' && meta.isSerialize === true) {
    config.data = serialize(config.data);
  }
  return config
}, error => {
  return Promise.reject(error)
});
//HTTPresponse拦截
axios.interceptors.response.use(res => {
  // 如果是 blob 类型响应（文件下载），直接返回
  if (res.config && res.config.responseType === 'blob') {
    // 检查是否是错误响应
    const contentType = res.headers['content-type'] || '';
    // 如果是 JSON 错误响应，则处理错误
    if (contentType.includes('application/json')) {
      // 将 blob 转换为文本以读取错误信息
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
          try {
            const result = JSON.parse(reader.result);
            Message({ message: result.message || 'Error', type: 'error', duration: 3000 });
            reject(new Error(result.message || 'Error'));
          } catch (e) {
            Message({ message: '导出失败', type: 'error', duration: 3000 });
            reject(new Error('导出失败'));
          }
        };
        reader.readAsText(res.data);
      });
    }
    // 正常的文件流，直接返回
    return res;
  }
  NProgress.close()
  const status =res.data.state || 500;
  const success =res.data.success || false;
  const statusWhiteList = website.statusWhiteList || [];
  const message = res.data.message || '未知错误';

  //如果在白名单里则自行catch逻辑处理
  if (statusWhiteList.includes(status)) {
    return Promise.reject(res);
  }
  if(success &&  (status==200 || status==201 || status==202)){
    return res;
  }

  //后台定义 424 针对令牌过期的特殊响应码
  if (status == 401) {
    store.dispatch('LogOut').then(() => router.push({ path: '/login' }));
    return ;
  }
  // 如果请求为非200否者默认统一处理

  if (status != 200) {
    if(status == -99){
      // ElMessage({
      //   message: message,
      //   type: 'error'
      // })
      return res;
    }else{
      ElMessage({
        message: message,
        type: 'error'
      })
      return Promise.reject(res.data)
    }
    return Promise.reject(new Error(message))
  }
  return res;
}, error => {
  NProgress.close()
  return Promise.reject(new Error(error));
})

export default axios;
